#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <pthread.h>
#include <functional>


// 传参，可以传递对象/结构体
//研究两个问题 1.线程的健壮性
//2.观察 thread id (会发现lwp 和 tid 不一样)
// 返回值

const int threadnum = 5;

using fun_t = std::function<void()>;

class ThreadData
{
public:
    ThreadData(const std::string &name, const uint64_t &ctime, const fun_t &f)
        : threadname(name), createtime(ctime), fun(f)
    {
    }

public:
    std::string threadname;
    uint64_t createtime;
    fun_t fun;
};

void *pthreadRun(void *args)
{
    // std::string threadname = (char *)args;
    // while (true)
    // {
    //     std::cout << "thread name : " << threadname << std::endl;
    //     sleep(1);
    // }
    ThreadData *td = (ThreadData *)args;
    while (true)
    {
        std::cout << "thread name :" << td->threadname << "createtime :" << td->createtime << std::endl;
        td->fun();


        //故意制造错误
        if(td->threadname == "Thread-4")
        {
            std::cout<< "触发处0错误!!!!" << std::endl;
            int a = 10;
            // a/=0;
        }
        sleep(1);
    }
}

void task()
{
    std::cout << "我是线程的一个大任务！" << std::endl;
    sleep(1);
}

int main()
{
    std::vector<pthread_t> tids;
    for (int i = 0; i < threadnum; i++)
    {
        pthread_t tid;
        char threadnames[128];
        snprintf(threadnames,sizeof(threadnames),"%s-%d","Thread",i);
        ThreadData *td = new ThreadData(threadnames,(uint64_t)time(nullptr),task);
        pthread_create(&tid, nullptr, pthreadRun, (void *)td);
        tids.push_back(tid);
        sleep(1);
    }

    std::cout << "tid :";
    for(const auto & tid : tids)
    {
        std::cout << tid << " ";
    }
    std::cout<< "----"<<std::endl;

    while (true)
    {
        std::cout << "main thread " << std::endl;
        sleep(3);
    }
    return 0;
}